using System;
using System.Collections.Generic;
using System.Xml;
using System.Diagnostics;

namespace TAAlert.Alerts
{
    public class AlertManager
    {
        static private readonly TraceSwitch traceM = new TraceSwitch("AlertManager", "Debug info for AlertManager class");
        private List<Alert> alertsM = new List<Alert>();

        public void loadAlertsFromXML(string fileName)
        {
            Debug.WriteLineIf(traceM.TraceInfo, "-->AlertManager.loaderAlertsFromXML(" + fileName + ")");
            alertsM.Clear();

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;
            using (XmlReader r = XmlReader.Create(fileName, settings))
            {
                r.MoveToContent();
                r.ReadStartElement("Alerts");
                while (r.NodeType == XmlNodeType.Element)
                {
                    Debug.WriteLineIf(traceM.TraceVerbose, "reading r.Name=" + r.Name);
                    StrategyName strategy = (StrategyName)Enum.Parse(typeof(StrategyName), r.Name);
                    switch (strategy)
                    {
                        case StrategyName.EMA:
                            alertsM.Add(new EMAAlert(r));
                            break;
                        case StrategyName.TwoEMA:
                            alertsM.Add(new TwoEmaAlert(r));
                            break;
                        case StrategyName.MACD:
                            alertsM.Add(new MACDAlert(r));
                            break;
                        case StrategyName.VEMA:
                            alertsM.Add(new VEMAAlert(r));
                            break;
                        default:
                            throw new XmlException("Unexpected node: " + r.Name);
                    }
                }
                r.ReadEndElement();
            }
        }

        public void saveAlertsToXML(string fileName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(fileName, settings))
            {
                writer.WriteStartElement("Alerts");
                foreach (Alert a in alertsM)
                {
                    writer.WriteStartElement(a.XmlName.ToString());
                    a.writeXml(writer);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }

        }

        public void addAlert(Alert alert)
        {
            alertsM.Add(alert);
        }

        public void removeAlert(Alert alert)
        {
            alertsM.Remove(alert);
        }

        public List<Alert> Alerts
        {
            get { return alertsM; }
        }
    }
}
